# -*- coding: utf-8 -*-
"""
@Time    : 2021/10/13 18:30
@Author  : Leibuyun
@File    : 6.1 读写CSV数据.py
"""

import csv
from collections import namedtuple

with open('res/stocks.csv') as f:
    f_csv = csv.reader(f)
    headers = next(f_csv)
    Row = namedtuple('Row', headers)
    print(headers)
    for row in f_csv:
        r = Row(*row)
        print(r)

# 将每一行的数据读入到一个字典序列中
# with open('res/stocks.csv') as f:
#     f_csv = csv.DictReader(f)
#     for row in f_csv:
#         print(row)


# 写入csv文件
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [{'Symbol': 'AA', 'Price': 39.48, 'Date': '6/11/2007',
         'Time': '9:36am', 'Change': -0.18, 'Volume': 181800},
        {'Symbol': 'AIG', 'Price': 71.38, 'Date': '6/11/2007',
         'Time': '9:36am', 'Change': -0.15, 'Volume': 195500},
        {'Symbol': 'AXP', 'Price': 62.58, 'Date': '6/11/2007',
         'Time': '9:36am', 'Change': -0.46, 'Volume': 935000},
        ]

with open('res/stocks2.csv', 'w') as f:
    f_csv = csv.DictWriter(f, headers)
    f_csv.writeheader()
    f_csv.writerows(rows)

